package com.mach.platform.api.service;

import com.mach.platform.api.domain.WxUser;
import com.mach.platform.api.repository.WxUserRepo;
import com.mach.platform.api.util.Base64Util;
import com.mach.platform.api.util.ImageUtil;
import com.mach.platform.service.CacheServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.File;

@Service
public class WxUserServiceImpl {

    @Autowired
    private WxUserRepo userRepo;

    @Autowired
    private CacheServiceImpl cacheService;

    /**
     * 获取用户信息
     * @param openId 用户openId
     * @return
     */
    public WxUser getWxUserInfo(String openId) {
        return userRepo.findByOpenId(openId);
    }


    /**
     * 修改用户头像地址
     * @param openId 用户openId
     * @param file 头像图片
     */
    public String updateAvatar(String openId, MultipartFile file) {
        File oldAvatar = ImageUtil.getAvatarImage(openId);
        oldAvatar.delete(); // 删除旧头像
        ImageUtil.uploadAvatar(openId, file); // 上传新头像
        return ImageUtil.getAvatarShowPath(openId);
    }


    /**
     * 修改用户昵称
     * @param nickName 用户昵称
     * @return
     */
    public void updateNickname(String openId, String nickName) {
        WxUser user = userRepo.findByOpenId(openId);
        nickName = Base64Util.base64Coding(nickName);
        user.setNickName(nickName);
        userRepo.save(user);
    }


    /**
     * 用户退出登录
     * @param openId
     */
    @Transactional(rollbackOn = Exception.class)
    public void signOut(String openId) {
        cacheService.removeCache(openId);
        userRepo.deleteByOpenId(openId);
    }

}
